package com.js.rtu.fragment.forth;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.js.rtu.R;
import com.js.rtu.adapter.HistoryDetailAdapter;
import com.js.rtu.adapter.HistoryListAdapter;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.greendao.DBHelper;
import com.js.rtu.greendao.dao.HistoryBeanDao;
import com.js.rtu.greendao.dao.HistoryInfoBeanDao;
import com.js.rtu.greendao.db.HistoryBean;
import com.js.rtu.greendao.db.HistoryInfoBean;
import com.js.rtu.mvp.bean.Cmd02Bean;
import com.js.rtu.mvp.bean.Cmd92Bean;
import com.js.rtu.mvp.bean.base.Cmd92_H18_Bean;
import com.js.rtu.mvp.bean.base.CommonBean;
import com.js.rtu.mvp.present.Cmd09Presenter;
import com.js.rtu.mvp.present.Cmd92Presenter;
import com.js.rtu.util.CSVUtil;
import com.js.rtu.util.ExcelUtil;
import com.tencent.bugly.proguard.A;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 历史记录列
 */
public class HistoryDetaiFragment extends BaseFragment {


    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rcy_list)
    RecyclerView rcyList;

    private HistoryInfoBean mHistoryInfoBean;

    private HistoryDetailAdapter mAdapter;


    private static final String ARG_BEAN = "list";

    Long id;

    public static HistoryDetaiFragment newInstance(Long id) {
        Bundle args = new Bundle();
        HistoryDetaiFragment fragment = new HistoryDetaiFragment();
        args.putLong(ARG_BEAN, id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getLong(ARG_BEAN);

        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_forth_history_detail;
    }


    @Override
    protected void initView() {
        toolbarTitle.setText("补调数据");
        initToolbarNav(toolbar);
        toolbar.inflateMenu(R.menu.menu_report);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.report:

                        toastShow("正在导出");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String MYLOG_PATH_SDCARD_DIR = "/sdcard/rtu/bd09";// 日志文件在sdcard中的路径
                                File dirsFile = new File(MYLOG_PATH_SDCARD_DIR);
                                if (!dirsFile.exists()){
                                    dirsFile.mkdirs();
                                }
                                List<HistoryBean> dataList = mAdapter.getData();
                                List<String> list = new ArrayList<>();
                                for (HistoryBean historyBean : dataList) {
                                    list.add(historyBean.getPos()+"---"+historyBean.getStartTime()+"---"+historyBean.getEndTime()+"---"+historyBean.getData());
                                }


                                try {
                                    CSVUtil.exportCsv(fileName, list);
                                    exportExcel(dataList);
                                } catch (IOException pE) {
                                    pE.printStackTrace();
                                }


                            }
                        }).start();
                        break;

                }


                return false;
            }
        });


        List<HistoryInfoBean> mList = DBHelper.getInstance().getSession().getHistoryInfoBeanDao().queryBuilder().
                where(HistoryInfoBeanDao.Properties.Id.eq(id)).list();
        if (mList.size() != 0) {
            mHistoryInfoBean = mList.get(0);



            List<HistoryBean> historyBeans = DBHelper.getInstance().getSession().getHistoryBeanDao().queryBuilder().
                    where(HistoryBeanDao.Properties.Time.eq(mHistoryInfoBean.getOperaTime())).list();

            mAdapter = new HistoryDetailAdapter(historyBeans);
            initRecyclerView(rcyList, mAdapter, 1);
            fileName = mHistoryInfoBean.getDeviceId() + "-" + new SimpleDateFormat("yyyy-MM-dd HH.mm.ss", Locale.CHINA).format(new Date());
        }else{
            fileName =  new SimpleDateFormat("yyyy-MM-dd HH.mm.ss", Locale.CHINA).format(new Date());
        }




    }


    private int oaMax = 0;
    private int obMax = 0;
    private int ocMax = 0;
    private int odMax = 0;
    private int oeMax = 0;
    private int ofMax = 0;


    private void exportExcel(List<HistoryBean> dataList) {
        String filePath = Environment.getExternalStorageDirectory().getPath() + "/rtu/bd09";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        oaMax = 0;
        obMax = 0;
        ocMax = 0;
        odMax = 0;
        oeMax = 0;
        ofMax = 0;
        List<CommonBean<List<Cmd02Bean>>> demoBeanList = new ArrayList<>();

        str_18H = new ArrayList<>();
        for (HistoryBean historyBean : dataList) {
            String[] data = historyBean.getData().split(" ");
            if (data.length >= 12 && data[12].equals("09") && historyBean.getIsSuccess()) {
                Cmd09Presenter cmd09Presenter = new Cmd09Presenter();
                CommonBean<List<Cmd02Bean>> commonBeanList = cmd09Presenter.paseData(historyBean.getData());

                if (mHistoryInfoBean != null && str_18H.size() == 0 && !mHistoryInfoBean.getConfig92().isEmpty()) {

                    Cmd92Presenter presenter = new Cmd92Presenter();
                    CommonBean<Cmd92Bean> bean = presenter.paseData(mHistoryInfoBean.getConfig92());
                    Cmd92Bean cmd92Bean = bean.getData();
                    str_18H = cmd92Bean.getStr_18H();
                }

                for (Cmd02Bean datum : commonBeanList.getData()) {
                    if (datum.getOAList()!=null&&datum.getOAList().size() > oaMax) {
                        oaMax = datum.getOAList().size();
                    }
                    if (datum.getOBList()!=null&&datum.getOBList().size() > obMax) {
                        obMax = datum.getOBList().size();
                    }
                    if (datum.getOCList()!=null&&datum.getOCList().size() > ocMax) {
                        ocMax = datum.getOCList().size();
                    }
                    if (datum.getODList()!=null&&datum.getODList().size() > odMax) {
                        odMax = datum.getODList().size();
                    }
                    if (datum.getOEList()!=null&&datum.getOEList().size() > oeMax) {
                        oeMax = datum.getOEList().size();
                    }
                    if (datum.getOFList()!=null&&datum.getOFList().size() > ofMax) {
                        ofMax = datum.getOFList().size();
                    }
                }

                demoBeanList.add(commonBeanList);
            }
        }

        String excelFileName = "/" + fileName + ".xls";
        List<String> name = new ArrayList<>();
        name.add("时间");
        name.add("DTU");
        for (int i = 0; i < oaMax; i++) {
            name.add("ai" + i);
        }
        for (int i = 0; i < obMax; i++) {
            name.add("bi" + i);
        }

        for (int i = 0; i < ocMax; i++) {
            name.add("ci" + i);
        }
        for (int i = 0; i < odMax; i++) {
            name.add("di" + i);
        }
        for (int i = 0; i < oeMax; i++) {
            name.add("ei" + i);
        }
        for (int i = 0; i < ofMax; i++) {
            name.add("fi" + i);
        }

        String[] title = new String[name.size()];
        title = name.toArray(title);

        String sheetName = fileName;


        filePath = filePath + excelFileName;
        ExcelUtil.initExcel(filePath, sheetName, title);
        ExcelUtil.writeObjListToExcel(getRecordData(demoBeanList), filePath, _mActivity);

    }

    /**
     * 将数据集合 转化成ArrayList<ArrayList<String>>
     *
     * @return
     */
    private ArrayList<ArrayList<String>> getRecordData(List<CommonBean<List<Cmd02Bean>>> demoBeanList) {
        List<Cmd02Bean> cmd02BeanList = new ArrayList<>();
        for (CommonBean<List<Cmd02Bean>> listCommonBean : demoBeanList) {
            for (Cmd02Bean datum : listCommonBean.getData()) {
                datum.setAddress(listCommonBean.getAddress());
                cmd02BeanList.add(datum);
            }
        }

        ArrayList<ArrayList<String>> recordList = new ArrayList<>();
        for (Cmd02Bean bean : cmd02BeanList) {
            ArrayList<String> beanList = new ArrayList<>();
            beanList.add(bean.getTime());
            beanList.add(bean.getAddress());
            if (bean.getOAList()!=null) {
                for (int i = 0; i < oaMax; i++) {
                    if (i > bean.getOAList().size()) {
                        beanList.add("无");
                    } else {
//                    beanList.add(bean.getOAList().get(i));
                        beanList.add(paseAI(i, bean.getOAList().get(i)));
                    }
                }
            }
            if (bean.getOBList()!=null) {
                for (int i = 0; i < obMax; i++) {
                    if (i > bean.getOBList().size()) {
                        beanList.add("无");
                    } else {
                        beanList.add(bean.getOBList().get(i));
                    }
                }
            }
            if (bean.getOCList()!=null) {
                for (int i = 0; i < ocMax; i++) {
                    if (i > bean.getOCList().size()) {
                        beanList.add("无");
                    } else {
                        beanList.add(bean.getOCList().get(i));
                    }
                }
            }
            if (bean.getODList()!=null) {
                for (int i = 0; i < odMax; i++) {
                    if (i > bean.getODList().size()) {
                        beanList.add("无");
                    } else {
                        beanList.add(bean.getODList().get(i));
                    }
                }
            }
            if (bean.getOEList()!=null) {
                for (int i = 0; i < oeMax; i++) {
                    if (i > bean.getOEList().size()) {
                        beanList.add("无");
                    } else {
                        beanList.add(bean.getOEList().get(i));
                    }
                }
            }
            if (bean.getOFList()!=null) {
                for (int i = 0; i < ofMax; i++) {
                    if (i > bean.getOFList().size()) {
                        beanList.add("无");
                    } else {
                        beanList.add(bean.getOFList().get(i));
                    }
                }
            }
            recordList.add(beanList);
        }
        return recordList;
    }

    private String fileName;


    List<Cmd92_H18_Bean> str_18H;//AI量程

    public String paseAI(int curPos, String ai) {
        if (oaMax < 4) {
            return ai;
        }
        //800-4000
        float d = Float.parseFloat(ai);
        if (curPos == 0) {//CSQ,0-255
            d = (d - 800) / 3200 * 255;//（信号强度值*3200）/255+800
            if (d <= 0) {
                d = 0;
            }
            if (d >= 255) {
                d = 255;
            }

        } else if (curPos == (oaMax - 2)) {//电压,0-3.7
            d = (d - 800) / 3200 * 3.7f;//（信号强度值*3200）/255+800
            if (d <= 0) {
                d = 0;
            }
            if (d >= 255) {
                d = 255;
            }
        } else if (curPos == (oaMax - 1)) {//温度，0-100
            d = (d - 800) / 3200 * 100;//（信号强度值*3200）/255+800
            if (d <= 0) {
                d = 0;
            }
            if (d >= 255) {
                d = 255;
            }

        } else {//ai
            Cmd92_H18_Bean bean = str_18H.get(curPos - 1);
            float max = Float.parseFloat(bean.getRangeMax());// 量程上限
            float min = Float.parseFloat(bean.getRangeMin());// 量程下限
            d = (d - 800) / 3200 * (max - min);
            if (d <= min) {
                d = min;
            }
            if (d >= max) {
                d = max;
            }
        }
        DecimalFormat fnum = new DecimalFormat("##0.0");
        String dd = fnum.format(d);
        return ai + "(" + dd + ")";
    }
}
